(: Parse thread HTML into something manageable. :)
import module namespace functx = "http://www.functx.com" at "WEB-INF/xquery/functx-1.0.xq";
declare variable $doc as node() external;

(:Thread metadata :)
let $title := $doc//title/text()

(: Find all posts, then drill down to produce xml for them. :)
let $posts := $doc//div[@id='posts']//table[starts-with(@id, 'post')]
let $postseq := 
    for $post in $posts
        (: Username definition is a bit strange; some names have font tags. Others don't :)
    	let $username := if (count($post//a[@class='bigusername']/font) != 0)
                         then $post//a[@class='bigusername']/font/text()
                         else $post//a[@class='bigusername']/text()[2] (: text() produces ("", name, "") :)
        
        (: Find and sanitize post content :)
        let $disallowed := ('img', 'embed', 'object')
        let $formatting := ('a', 'i', 'b', 'u', 'strong', 'em', 'font', 'table')
        let $content := for $node in $post//div[starts-with(@id, 'post_message_')]/node()
                            let $sanitized := functx:remove-elements-deep($node, $disallowed)
                            return functx:remove-elements-not-contents($sanitized, $formatting)
        
    	return
    	<post>
            <user>{functx:trim($username)}</user>
            <contents>
                {$content}
            </contents>    
        </post>
        
return 
<posts title="{$title}">
    {$postseq}
</posts>